package com.whq.thrift.api.kafka.requestlog.job;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.whq.common.DateUtil;
import com.whq.thrift.api.common.constants.CommonConfigConstants;
import com.whq.thrift.api.common.spring.ReloadableConfManager;
import com.whq.thrift.api.kafka.requestlog.db.RequestLog;
import com.whq.thrift.api.kafka.requestlog.service.RequestLogService;

@Service
public class ClearOldRequestLogJob {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ClearOldRequestLogJob.class);
	private static final Logger LOGGER_QUARTZ = LoggerFactory.getLogger(CommonConfigConstants.LOGGER_KEY_QUARTZ);
	
	@Autowired
	private ReloadableConfManager reloadableConfManager;
	
	@Autowired
	RequestLogService requestLogService;
	
	public void removeOldRequestLogData() {
		LOGGER_QUARTZ.info("begin remove old request log");
		String retainMaxDays = reloadableConfManager.getPropertyValue("requestlog.retain.max.days", null);
		
		int iRetainMaxDays = 0;
		try {
			iRetainMaxDays = Integer.valueOf(retainMaxDays);
		} catch (Exception e) {
			LOGGER.error("translate [" + retainMaxDays + "] to int exception", e);
		}
		
		LOGGER_QUARTZ.info("will delete " + iRetainMaxDays + " days before request logs");
		
		List<Integer> tableSeqList = RequestLog.getAllTableSeqList();
		for (Iterator<Integer> iterator = tableSeqList.iterator(); iterator.hasNext();) {
			Integer tableSeq = (Integer) iterator.next();
			if (tableSeq == null) {
				continue;
			}
			Date now = new Date();
			Date time = DateUtil.getOffsetDateBegin(now, 0 - iRetainMaxDays);
			
			LOGGER_QUARTZ.info("will delete before [" + time + "] request logs");
			
			requestLogService.delRequestLogsByBeforeTime(tableSeq, time);
		}
		LOGGER_QUARTZ.info("end remove old request log");
	}
}
